(function ($) {
    'use strict';

    /**
     * jqGrid column model template
     * {
     *    colModel: [
     *      { name: 'xxx', index:'xxx', template: 'actions2' }
     *    ]
     * }
     *
     * {@see grid.base.js#jqGrid}
     */
    $.jgrid.cmTemplate = $.extend($.jgrid.cmTemplate, {
        actions2: { sortable: false, resizable: false, search: false, formatter: 'actions2', align: 'center', width: 70 },
        img: { sortable: false, search: false, formatter: 'img', align: 'center', type: 'S' },
        bool: { formatter: 'checkbox', edittype: 'checkbox', editoptions: {value: '1:是;0:否'}, defaultValue: '0', stype: 'select'/*, dataUrl, surl*/, searchoptions: { value: ':全部;1:是;0:否' }, align: 'center', type: 'B' },
        // enum: { align: 'center', formatter: 'checkbox', editable: true, edittype: 'select', editoptions: { value: 'v1:Text1;v2:Text2', defaultValue: 'v2' } },
        num: { formatter: 'number', align: 'right', sorttype: 'number', searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn'] }, type: 'N' },
        int: { formatter: 'integer', align: 'right', sorttype: 'number', searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn'] }, type: 'I' },
        text: { stype: 'text', searchoptions: { sopt: ['bw', 'bn', 'ew', 'en', 'cn', 'nc', 'nu', 'nn', 'eq', 'ne' /*, 'in', 'ni'*/] }, align: 'left', type: 'S' },
        link: { formatter: 'link', formatoptions: { target: '_blank' }, stype: 'text', searchoptions: { sopt: ['bw', 'bn', 'ew', 'en', 'cn', 'nc', 'nu', 'nn', 'eq', 'ne' /*, 'in', 'ni'*/] }, align: 'left', type: 'S' },
        // date2: { formatter: 'date2', type: 'D' },
        date: {
            align: 'center', formatter: 'date', formatoptions: { srcformat: 'ms' /*, newformat: 'd-m-Y'*/ },
            stype: 'custom', searchoptions: {
                sopt: ['eq'],
                dopt: {dateFmt: 'yyyy-MM-dd'},
                custom_element: function (defaultValue, options) {
                    var me = this;
                    return $('<input type="text" class="Wdate" style="width: 100%;">')
                        .on('keypress change', function (e) {
                            var key = e.charCode || e.keyCode || 0;
                            if (key === 13) {
                                me.triggerToolbar();
                                return false;
                            }
                            return this;
                        }).on('focus click', function (e) {
                            window.WdatePicker && WdatePicker($.extend({
                                el: this,
                                dateFmt: 'yyyy-MM-dd',
                                readOnly: true,
                                doubleCalendar: false,
                                onpicked: $.proxy(me.triggerToolbar, me),
                                oncleared: $.proxy(me.triggerToolbar, me)
                                // maxDate:'#F{$dp.$D(\'endDate\')||\'2099-12-31\'}'
                            }, options.dopt));
                        });
                },
                custom_value: function ($el, action, value) {
                    return 'set' == action ? $el.val(value || "") : $el.val();
                }
            }, type: 'D'
        }
    });

    /**
     * jqGrid formatter
     * {
     *  colModel: [
     *      { formatter: 'img' }
     *  ]
     * }
     * {@see grid.fmatter.js}
     */
    $.fn.fmatter = $.extend($.fn.fmatter, {
        img: function (val, opts, rwd, act) {
            if (!val) return "";

            var op = { w: 100, h: 80 };
            if (opts.colModel !== undefined && opts.colModel.formatoptions !== undefined) {
                op = $.extend({}, op, opts.colModel.formatoptions);
            }
            return '<img src="' + val + '" width="' + op.w + '" height="' + op.h + '">';
        },
        actions2: function (value, opts) {
            var ctx = (window.Besture || window)['contextPath'] || '';
            return '<div class="operateBox">' +
                '<img onclick="jQuery.fn.fmatter.rowactions2.call(this, \'edit\');" src="' + ctx + '/images/admin/icon-edit01.png" width="15" height="15" title="Edit" alt="Edit">' +
                '<img onclick="jQuery.fn.fmatter.rowactions2.call(this, \'del\');" src="' + ctx + '/images/admin/icon-delete01.png" width="15" height="15" title="Delete" alt="Delete">' +
                '</div>';
        },
        rowactions2: function (act) {
            var $tr = $(this).closest("tr.jqgrow"),
                rid = $tr.attr("id"),
                $id = $(this).closest("table.ui-jqgrid-btable").attr('id').replace(/_frozen([^_]*)$/, '$1'),
                $grid = $("#" + $id),
                op = {
                    extraparam: {}
                };

            switch (act) {
                case 'del':
                    Besture.Messager.confirm('警告', '您确定要删除选中的记录吗？', function (r) {
                        if (!r) return;
                        // $grid.jqGrid('delGridRow', rid, op.delOptions);
                        // $grid.jqGrid('delRowData', rid);
                        /*
                        $.ajax({
                            traditional: true,
                            data: {id: }
                        })
                        $grid.trigger('reloadGrid');
                        */
                    });
                    break;
                case 'edit':
                    break;
            }
        }
    });

    (function () {
        var _parseDate = $.jgrid.parseDate;
        // $.jgrid.fmatter.date -> $.jgrid.formatter.date.masks 提供的无法处理 ms 和 $.jgrid.parseDate
        $.jgrid.parseDate = function (format, date, newformat, opts) {
            if (/*'ms' == format && */typeof date === 'number') {
                date = new Date(date);
            }
            return _parseDate.call(this, format, date, newformat, opts);
        };
    })();

    // 执行搜索前将搜索转换为特定的格式
    $.jgrid.extend({
        _: function () {
            var $self = this,
                me = $self[0];

            function clear() {
                var postData = me.p.postData;
                for (var p in postData) {
                    if (/^search_/.test(p) && postData.hasOwnProperty(p)) {
                        delete postData[p];
                    }
                }
            }

            $self.on('jqGridToolbarBeforeSearch', function () {
                var me = this,
                    postData = me.p.postData,
                    filters = $.extend({rules: []}, $.parseJSON(postData.filters));

                function getType(field) {
                    var cm = me.p.colModel, i;
                    for (i = 0; i < cm.length; i++) {
                        if (cm[i].name === field) {
                            return cm[i].type || 'S';
                        }
                    }
                    return 'S';
                }

                clear();
                $.each(filters.rules, function (i, rule) {
                    var key = "search_" + rule.field + '_' + rule.op + '_' + getType(rule.field);
                    if (postData[key]) {
                        postData[key] = $.isArray(postData[key]) ? postData[key].push(rule.data) : [postData[key], rule.data];
                    } else {
                        postData[key] = rule.data;
                    }
                });
            }).on('jqGridToolbarBeforeClear', clear);
            return this;
        }
    });
    /**
     * jqGrid defaults
     *
     * {@see }
     */
    $.jgrid.defaults = $.extend($.jgrid.defaults, {
        mtype: 'post',
        // height: 'auto',
        altRows: true,
        gridview: true,
        rownumbers: true,
        rowNum: 10,
        rowList: [5, 10, 15],
        viewrecords: true,
        // pginput: false,
        recordpos: 'right',
        pagerpos: 'center',
        prmNames: { page: 'page', rows: "size", sort: "sort", order: "order" },
        sortname: 'id', // 默认排序字段
        sortorder: "asc",
        jsonReader: {
            root: 'data',            // 数据根
            page: 'page',            // 当前页码
            total: 'totalPages',     // 总page
            records: 'total',       // 总记录
            repeatitems: false      // 数据不可重复
        },
        /*gridComplete*/onInitGrid: function () {
            var me = this,
                p = me.p,
                $self = $(me);

            // 一些常规化处理
            // 如果有分页条的话在分页条上..
            p.pager && $self.jqGrid('navGrid', p.pager);
            $self.jqGrid('filterToolbar', { searchOperators: true }).jqGrid('_');
        }
    });

    /**
     * {@see grid.formedit.js#navGrid}
     */
    $.jgrid.nav = $.extend($.jgrid.nav, {
        edit: false,
        add: false,
        del: false,
        search: false,
        refresh: true,
        refreshicon: "ui-icon-refresh",
        refreshstate: 'firstpage',
        position: "left",
        beforeRefresh: null,
        afterRefresh: null,
        cloneToTop: false
    });

})(jQuery);
